<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" layout:decorator="layout/default">
<head>
    <meta charset="UTF-8">
    <style type="text/css">
        #connect-container {
            margin: 0 auto;
            width: 400px;
        }

        #connect-container div {
            padding: 5px;
            margin: 0 7px 10px 0;
        }

        .layui-btn {
            display: inline-block;
        }
    </style>

</head>
<section layout:fragment="content">
    <div>
        <div id="connect-container" class="layui-elem-field">
            <legend>Echo</legend>
            <div>
                <textarea id="message" class="layui-textarea" placeholder="请输入请求的内容" style="width: 350px"></textarea>
            </div>
            <div>
                <button id="echo" class="layui-btn layui-btn-normal"
                        onclick="echo();">Echo message
                </button>
            </div>
        </div>
    </div>
    <script th:src="@{/layui/layui.js}"></script>
    <script type="text/javascript">
        let ws = null;
        //断开连接
        function disconnect() {
            if (ws != null) {
                ws.close();
                ws = null;
            }
        }
        function echo() {
            if (ws != null) {
                let message = $("#message").val();
                console.log('Sent: ' + message);
                ws.send(message);
            } else {
                console.log('WebSocket connection not established, please connect.');
            }
        }
        $(function () {
            if (window.location.protocol === 'http:') {
                ws = new WebSocket('ws://' + window.location.host +'/eycMessage');
            } else {
                ws = new WebSocket('wss://' + window.location.host + '/eycMessage');
            }
            ws.onopen = function () {
                console.log('Info: WebSocket connection opened.');
            };
            ws.onmessage = function (event) {
                console.log('Received: ' + event.data);
                layer.open({
                    content: event.data,
                    offset: 'rb'
                });
            };
            ws.onclose = function () {
                console.log('Info: WebSocket connection closed.');
            };
            layui.use([], function () {

            });
        });



    </script>
</section>
</html>